﻿<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map.Entry,java.util.*,java.util.regex.*,java.net.*,java.io.*,java.text.*"%>
<%@ page import="com.tianxiabuyi.*,com.tianxiabuyi.db.*,com.tianxiabuyi.model.*,com.tianxiabuyi.util.*"%>
<%@ page import="org.jsoup.Jsoup,org.jsoup.nodes.Element,org.jsoup.select.Elements"%>
<%@ page import="com.google.gson.reflect.TypeToken"%>
<%@ page import="org.dom4j.*"%>
<%@ page import="net.sourceforge.pinyin4j.PinyinHelper"%>
<%@ page import="net.sourceforge.pinyin4j.format.*"%>
<%@ page import="net.sourceforge.pinyin4j.format.exception.*"%>
<%!
	/**
		app使用的通讯录
		传入参数:
			hospital:(必选)
			dept: (可选，如果不传，则返回该医院的全部科室的联系人)
	*/
	String contacts(Input input) {
		Integer id = input.getInt("id", -1);
		String hospital = input.getDesc("hospital", "");
		String dept = "";
		Message msg = new Message();
		if (id != -1) {
			dept = "deptId = " + id + "";
		}
		List<Contact> list = QBuilder.db("basedb").select().from("Contact").where(new Where("hospital=", hospital).and(dept).and("status=", STATUS_ENABLE)).order("deptId", "asc").query().getResultObj();
		if ( list.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg.toJson();
		}
		List<Dept> deptList = QBuilder.db("basedb").queryHql("from Dept where hospital = " + hospital + " and type=" + DEPT_CONTACT + " and status=" + STATUS_ENABLE + " order by id");
		List<Dept> depts = new ArrayList<Dept>();
		if (id != -1) {
			for (int i =0; i <deptList.size();i++) {
				if (id.equals(deptList.get(i).getId())) {
					depts.add(deptList.get(i));
				}
			}
			deptList = depts;
		}
		Map<Integer, String> deptMap = new HashMap<Integer, String>();
		for (Dept d:deptList) {
			deptMap.put(d.getId(), d.getDeptName());
		}
		LinkedHashMap contacts = new LinkedHashMap();
		for (Dept d:deptList) {
			Integer deptId = d.getId();
			List deptContacts = new ArrayList();
			for (Contact con : list) {
				Integer did = con.getDeptId();
				if (!did.equals(deptId)) {
					continue;
				}
				Map map = GsonUtil.fromJson(GsonUtil.toJson(con), new TypeToken<Map>(){});
				String userName = Tools.getDesc(map.get("username") + "");
				map.put("name_pinyin", getPinYin(userName));
				map.put("name_pinyin_headchar", getPinYinHeadChar(userName));
				map.put("dept", deptMap.get(deptId));
				map.put("hospital", hospital);
				map.put("ID", Tools.getInt(map.get("id") + ""));//应iOS开发要求，iOS中"id"为系统变量，所以用ID代替
				map.put("remarks", con.getJson());//应前台要求，将json字段替换为remarks
				map.remove("json");
				map.remove("id");
				map.remove("create_time");
				map.remove("dept_id");
				map.remove("status");
				deptContacts.add(map);
			}
			if (id != -1) {
				msg.put("contacts", deptContacts);
				return  msg.toJson();
			}
			contacts.put(deptMap.get(deptId), deptContacts);
		}

		msg.put("contacts", contacts);
		return  msg.toJson();
	}
	
	/**
		app使用的通讯录(兼容ios)
		传入参数:
			hospital:(必选)
			dept: (可选，如果不传，则返回该医院的全部科室的联系人)
	*/
	String contactList(Input input) {
		Integer id = input.getInt("id", -1);
		String hospital = input.getDesc("hospital", "");
		String dept = "";
		Message msg = new Message();
		if (id != -1) {
			dept = "deptId = " + id + "";
		}
		List<Contact> list = QBuilder.db("basedb").select().from("Contact").where(new Where("hospital=", hospital).and(dept).and("status=", STATUS_ENABLE)).order("deptId", "asc").query().getResultObj();
		if ( list.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg.toJson();
		}
		List<Dept> deptList = QBuilder.db("basedb").queryHql("from Dept where hospital = " + hospital + " and type=" + DEPT_CONTACT + " and status=" + STATUS_ENABLE + " order by id");
		List<Dept> depts = new ArrayList<Dept>();
		if (id != -1) {
			for (int i =0; i <deptList.size();i++) {
				if (id.equals(deptList.get(i).getId())) {
					depts.add(deptList.get(i));
				}
			}
			deptList = depts;
		}
		Map<Integer, String> deptMap = new HashMap<Integer, String>();
		for (Dept d:deptList) {
			deptMap.put(d.getId(), d.getDeptName());
		}
		List contacts = new ArrayList();
		for (Dept d:deptList) {
			Integer deptId = d.getId();
			List deptContacts = new ArrayList();
			for (Contact con : list) {
				Integer did = con.getDeptId();
				if (!did.equals(deptId)) {
					continue;
				}
				Map map = GsonUtil.fromJson(GsonUtil.toJson(con), new TypeToken<Map>(){});
				String userName = Tools.getDesc(map.get("username") + "");
				map.put("name_pinyin", getPinYin(userName));
				map.put("name_pinyin_headchar", getPinYinHeadChar(userName));
				map.put("dept", deptMap.get(deptId));
				map.put("hospital", hospital);
				map.put("ID", Tools.getInt(map.get("id") + ""));//应iOS开发要求，iOS中"id"为系统变量，所以用ID代替
				map.put("remarks", con.getJson());//应前台要求，将json字段替换为remarks
				map.remove("json");
				map.remove("id");
				map.remove("create_time");
				map.remove("dept_id");
				map.remove("status");
				deptContacts.add(map);
			}
			if (id != -1) {
				msg.put("contacts", deptContacts);
				return  msg.toJson();
			}
			Map contactMap = new HashMap();
			contactMap.put("dept_name", deptMap.get(deptId));
			contactMap.put("list", deptContacts);
			contacts.add(contactMap);
		}

		msg.put("contacts", contacts);
		return  msg.toJson();
	}

	// 检索，姓名汉字，首字母，拼音
	String search (Input input) {
		String hospital = input.getDesc("hospital", "");
		String content = input.getDesc("content", "");
		Message msg = new Message();
		List<Contact> list = QBuilder.db("basedb").select().from("Contact").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE)).query().getResultObj();
		List deptContacts = new ArrayList();
		for (Contact con : list) {
			Map map = GsonUtil.fromJson(GsonUtil.toJson(con), new TypeToken<Map>(){});
			String userName = Tools.getDesc(map.get("username") + "");
			map.put("name_pinyin", getPinYin(userName));
			map.put("name_pinyin_headchar", getPinYinHeadChar(userName));
			map.put("hospital", hospital);
			map.put("ID", Tools.getInt(map.get("id") + ""));//应iOS开发要求，iOS中"id"为系统变量，所以用ID代替
			map.put("remarks", con.getJson());//应前台要求，将json字段替换为remarks
			map.remove("json");
			map.remove("id");
			map.remove("create_time");
			map.remove("status");
			deptContacts.add(map);
		}
		List<Dept> depts = QBuilder.db("basedb").select().from("Dept").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("type=", DEPT_CONTACT)).query().getResultObj();
		Map<Integer, String> deptMap = new HashMap<Integer, String>();
		for (Dept dept:depts) {
			deptMap.put(dept.getId(), dept.getDeptName());
		} 
		Iterator<Map> conIter = deptContacts.iterator();
        while (conIter.hasNext()) {
            Map map = conIter.next();
			map.put("dept_name", deptMap.get(((Double)map.get("dept_id")).intValue()));
			map.remove("dept_id");
            if (!Tools.getDesc(map.get("name_pinyin")).contains(content) && !Tools.getDesc(map.get("name_pinyin_headchar")).contains(content) && !Tools.getDesc(map.get("username")).contains(content))  {
				conIter.remove();
			}
        }
		msg.put("contacts", deptContacts);
		return  msg.toJson();
	}

	// 通讯录科室列表，APP和后台管理使用
	String deptList(Input input) {
		Integer hospital = input.getInt("hospital", -1); // 医院id
		String selectContent = "distinct new map(id as id, deptId as dept_id, deptName as dept_name, parent as parent)";
		List<Map> depts = QBuilder.db("basedb").select(selectContent).from("Dept").where(new Where("hospital=", hospital).and("status = ", STATUS_ENABLE).and("type=", DEPT_CONTACT)).query().getResultObj();
		Message msg = new Message(0);
		msg.put("depts", depts);
		List<Map> parentDepts = QBuilder.db("basedb").select(selectContent).from("Dept").where(new Where("hospital=", hospital).and("status = ", STATUS_ENABLE).and("type=", DEPT_CONTACT).and("parent = -1")).query().getResultObj();
		for (Map parent:parentDepts) {
			List<Map> list = new ArrayList<Map>();
			for (Map dept:depts) {
				if (Tools.getDesc(dept.get("parent")).equals(Tools.getDesc(parent.get("dept_id")))) {
					list.add(dept);
				}
			}
			parent.put("sub", list);
		}
		// 增加大小科室返回
		msg.put("all", parentDepts);
		return msg.toJson();
	}

	// 添加联系人,后台管理使用
	public String add(Input input) {
		Message msg = new Message();
		String phone = input.getDesc("mobile_phone","-1");
		String hospital  =  input.getDesc("hospital","-1");
		String hql = "From User where phone ='"+phone+"' and status = 1 and hospital ="+hospital;
		List<User> list = QBuilder.db("basedb").queryHql(hql);
		Integer id = -1;
		if(list != null && list.size() >0){
			id = list.get(0).getId();
		}

		Contact con = Contact.fromMap(input.getParameters(), Contact.class);
		con.setUid(id+"");

		try {
			DBTools.db("basedb").addItem(con);
		} catch(Exception e) {
			setErrcode(msg, RESPONSE_FAILED);
			return msg.toJson();
		}
		return msg.toJson();
	}
	// 删除联系人,后台管理使用
	public String delete(Input input) {
		Message msg = new Message();
		Integer id = input.getInt("id", -1);
		try {
			List<Contact> list = QBuilder.db("basedb").queryHql("from Contact where id = " + id);
			if (list.size() != 0) {
				Contact con = list.get(0);
				con.setStatus(STATUS_DISABLE);
				DBTools.db("basedb").modItem(con, con.getId());
			} else {
				setErrcode(msg, RESPONSE_FAILED);
				return msg.toJson();
			}
		} catch (Exception e) {
			setErrcode(msg, RESPONSE_FAILED);
			return msg.toJson();
		}
		return msg.toJson();
	}
	// 修改联系人,后台管理使用
	public String edit(Input input) {
		Message msg = new Message();
		Integer id = input.getInt("id", -1);
		String phone = input.getDesc("mobile_phone","-1");
		String hospital  =  input.getDesc("hospital","-1");
		String hql = "From User where phone ='"+phone+"' and status = 1 and hospital ="+hospital;
		List<User> list1 = QBuilder.db("basedb").queryHql(hql);
		Integer uid = -1;
		if(list1 != null && list1.size() >0){
			uid = list1.get(0).getId();
		}

		Contact con = Contact.fromMap(input.getParameters(), Contact.class);
		con.setUid(uid+"");
		try {
			List<Contact> list = QBuilder.db("basedb").queryHql("from Contact where id = " + id);
			if (list.size() == 0) {
				setErrcode(msg, RESPONSE_FAILED);
				return msg.toJson();
			}
			DBTools.db("basedb").modItem(con, id);
		} catch (Exception e) {
			setErrcode(msg, RESPONSE_FAILED);
			return msg.toJson();
		}
		return msg.toJson();
	}

	// 创建通讯录科室
	public String createDept(Input input) {
		Message msg = new Message();
		Dept dept = Dept.fromMap(input.getParameters(), Dept.class);
		dept.setType(DEPT_CONTACT);
		try {
			List<Dept> list = QBuilder.db("basedb").queryHql("from Dept where deptName = '" + dept.getDeptName() + "' and hospital = " + dept.getHospital() + " and status=" + STATUS_ENABLE);
			if (list.size() != 0) {
				return new Message(1001, "科室已存在").toJson();
			}
			DBTools.db("basedb").addItem(dept);
		} catch (Exception e) {
			setErrcode(msg, RESPONSE_FAILED);
			return msg.toJson();
		}
		return msg.toJson();
	}

	// 通讯录列表,后台管理使用
	String list(Input input) {
		Integer page = 1; // 页码
		Integer itemCount = 20; // 每一页条目
		Integer hospital = input.getInt("hospital", -1); // 医院id
		String sinceID = input.getDesc("since_id", "0"); // 下拉刷新
		String maxID = input.getDesc("max_id", "0"); // 上拉加载
		String dept = input.getDesc("dept_id", "");
		dept = "dept_id = " + dept + "";
		String order = "desc"; // 排序
		String id = "";
		if (!sinceID.equals("0")) {
			id = "id > " + sinceID;
			order = "asc";
		} else if (!maxID.equals("0")) {
			id = "id < " + maxID;
		}
		List contacts = QBuilder.db("basedb").select().from("Contact").where(new Where("hospital=", hospital).and("status = ", STATUS_ENABLE).and(id).and(dept)).order("id", order).page(itemCount, page).query().getResultObj();
		if (order.equals("asc")) { // 上拉加载时倒序
			Collections.reverse(contacts);
		}
		Message msg = new Message(0);
		msg.put("contacts", contacts);
		return msg.toJson();
	}

	// 通讯录详情，后台管理使用
	String contact(Input input) {
		Integer hospital = input.getInt("hospital", -1); // 医院id
		Integer id = input.getInt("id", -1); // id
		List contacts = QBuilder.db("basedb").select().from("Contact").where(new Where("hospital=", hospital).and("id =", id).and("status = ", STATUS_ENABLE)).query().getResultObj();
		Message msg = new Message(0);
		if (contacts.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg.toJson();
		}
		msg.put("contact", contacts.get(0));
		return msg.toJson();
	}


	//将汉字转换为全拼
	public static String getPinYin(String src) {
		char[] ch = null;
		ch = src.toCharArray();
		String[] str = new String[ch.length];
		HanyuPinyinOutputFormat output = new HanyuPinyinOutputFormat();
		output.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		output.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		output.setVCharType(HanyuPinyinVCharType.WITH_V);
		String pinYin = "";
		int len = ch.length;
		try {
			for (int i = 0; i < len; i++) {
				// 判断是否为汉字字符
				if (java.lang.Character.toString(ch[i]).matches("[\\u4E00-\\u9FA5]+")) {
					str = PinyinHelper.toHanyuPinyinStringArray(ch[i], output);
					pinYin += str[0];
				} else
					pinYin += java.lang.Character.toString(ch[i]);
			}
			return pinYin;
		} catch (BadHanyuPinyinOutputFormatCombination e1) {
			e1.printStackTrace();
		}
		return pinYin;
	}

	//返回中文的首字母
	public static String getPinYinHeadChar(String str) {
		String convert = "";
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert += pinyinArray[0].charAt(0);
			} else {
				convert += word;
			}
		}
		return convert;
	}
%>